package com.eastseeway.radioproject.calibration;

import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;

import com.eastseeway.radioproject.R;
import com.eastseeway.radioproject.base.BaseActivity;
import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.databinding.ActivityCalibrationBinding;
import com.eastseeway.radioproject.engineer.EngineerItemAdapter;
import com.eastseeway.radioproject.engineer.EngineerItemBean;
import com.eastseeway.radioproject.entities.Bean1FromHandle;
import com.eastseeway.radioproject.entities.BeanFromNegativePressureBoard;
import com.eastseeway.radioproject.entities.BeanOfAutoCalibration;
import com.eastseeway.radioproject.entities.BeanVBus;
import com.eastseeway.radioproject.entities.MessageEvent;
import com.eastseeway.radioproject.utils.SaveHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CalibrationActivity extends BaseActivity<ActivityCalibrationBinding,CalibrationViewModel> {

    private CalibrationItemAdapter mP1RvAdapter,mP2RvAdapter,mNp2RvAdapter,mNp1RvAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_calibration;
    }

    @Override
    protected Class<CalibrationViewModel> getVMClass() {
        return CalibrationViewModel.class;
    }

    @Override
    protected void observeData() {
        super.observeData();
        mViewModel.queryP1().observe(this,beanVBuses -> {
            mP1RvAdapter.submitList(beanVBuses);
        });
        mViewModel.queryP2().observe(this,beanVBuses -> {
            mP2RvAdapter.submitList(beanVBuses);
        });
        mViewModel.queryNP1().observe(this,beanVBuses -> {
            mNp1RvAdapter.submitList(beanVBuses);
        });
        mViewModel.queryNP2().observe(this,beanVBuses -> {
            mNp2RvAdapter.submitList(beanVBuses);
        });
        mViewModel.getPower().observe(this,power->{
            mViewModel.getPhaseVoltage().setValue(Const.CALIBRATION_DATA[power-1]);
        });

        mBinding.saveVBusToFile.setOnClickListener(v -> {
            if (mP1RvAdapter.getCurrentList().isEmpty() || mP2RvAdapter.getCurrentList().isEmpty() || mNp1RvAdapter.getCurrentList().isEmpty() || mNp2RvAdapter.getCurrentList().isEmpty()) {
                Toast.makeText(this,"数据为空",Toast.LENGTH_SHORT).show();
                return;
            }
            // 在子线程中执行保存操作
            new Thread(() -> {
                try {
                    List<BeanVBus> beanVBusList = new ArrayList<>();
                    beanVBusList.addAll(mP1RvAdapter.getCurrentList());
                    beanVBusList.addAll(mP2RvAdapter.getCurrentList());
                    beanVBusList.addAll(mNp1RvAdapter.getCurrentList());
                    beanVBusList.addAll(mNp2RvAdapter.getCurrentList());
                    String filePath = SaveHelper.getVBusFileName();
                    String jsonContent = new Gson().toJson(beanVBusList);

                    // 调用保存方法并获取返回值
                    boolean isSuccess = SaveHelper.write2File(filePath, jsonContent);

                    // 在主线程中更新UI
                    runOnUiThread(() -> {
                        if (isSuccess) {
                            Toast.makeText(CalibrationActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(CalibrationActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(() -> {
                        Toast.makeText(CalibrationActivity.this, "保存异常: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            }).start();
        });

        mBinding.restoreVBusFromFile.setOnClickListener(v -> {
            new Thread(() -> {
                try {
                    String filePath = SaveHelper.getVBusFileName();
                    // 使用SaveHelper中的读取方法
                    String jsonContent = SaveHelper.readFromFile(filePath);

                    if (jsonContent == null) {
                        runOnUiThread(() -> {
                            Toast.makeText(CalibrationActivity.this, "文件不存在或读取失败", Toast.LENGTH_SHORT).show();
                        });
                        return;
                    }

                    // 解析JSON数据
                    try {
                        Gson gson = new Gson();
                        Type listType = new TypeToken<List<BeanVBus>>(){}.getType();
                        List<BeanVBus> restoredList = gson.fromJson(jsonContent, listType);

                        if (restoredList != null) {
                            mViewModel.insertVBusList(restoredList);
                        } else {
                            runOnUiThread(() -> {
                                Toast.makeText(CalibrationActivity.this, "数据解析失败", Toast.LENGTH_SHORT).show();
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(() -> {
                            Toast.makeText(CalibrationActivity.this, "数据解析异常: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(() -> {
                        Toast.makeText(CalibrationActivity.this, "恢复异常: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            }).start();
        });

        mBinding.back.setOnClickListener(v -> finish());
    }

    @Override
    protected void loadData() {
        super.loadData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mBinding.setMViewModel(mViewModel);
        mBinding.np1Rv.setLayoutManager(new GridLayoutManager(this,5));
        mNp1RvAdapter = new CalibrationItemAdapter();
        mBinding.np1Rv.setAdapter(mNp1RvAdapter);

        mBinding.np2Rv.setLayoutManager(new GridLayoutManager(this,5));
        mNp2RvAdapter = new CalibrationItemAdapter();
        mBinding.np2Rv.setAdapter(mNp2RvAdapter);

        mBinding.p1Rv.setLayoutManager(new GridLayoutManager(this,5));
        mP1RvAdapter = new CalibrationItemAdapter();
        mBinding.p1Rv.setAdapter(mP1RvAdapter);

        mBinding.p2Rv.setLayoutManager(new GridLayoutManager(this,5));
        mP2RvAdapter = new CalibrationItemAdapter();
        mBinding.p2Rv.setAdapter(mP2RvAdapter);

        mBinding.clear.setOnClickListener(v -> {
            new AlertDialog.Builder(this)
                    .setTitle("是否删除？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        mViewModel.onClear();
                    }).setNegativeButton("取消", null).show();
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OnEvent(MessageEvent messageEvent){
        int messageEventCode = messageEvent.getCode();
        if (messageEventCode == Const.ADDRESS_FROM_NEGATIVE_PRESSURE_BOARD) {
            BeanFromNegativePressureBoard beanFromNegativePressureBoard = (BeanFromNegativePressureBoard) messageEvent.getData();
            String pressureStringBuffer = "储气罐传感器压力值:" + beanFromNegativePressureBoard.getGas_Container_Press() + "\n" +
                    "手柄连接传感器管路压力值:" + beanFromNegativePressureBoard.getGas_Pipe_Press() + "\n" +
                    "手柄端请求的压力值:" + beanFromNegativePressureBoard.getHandle_Gas_Press() + "\n";
            mViewModel.getPressure_info().setValue(pressureStringBuffer);
        }else if (messageEventCode == Const.ADDRESS_FROM_HANDLE_1_DATA_1) {
            Bean1FromHandle bean1FromHandle = (Bean1FromHandle) messageEvent.getData();
            mViewModel.getHandle_info().setValue("手柄返回的压力值：" + bean1FromHandle.getPressure());
        }else if (messageEventCode == Const.ADDRESS_FROM_AUTO_CALIBRATION) {
            BeanOfAutoCalibration beanOfAutoCalibration = (BeanOfAutoCalibration) messageEvent.getData();
            if (beanOfAutoCalibration.getCmd_type() == 1) {
                mViewModel.getAutoState().setValue("正在自动校准");
                if (beanOfAutoCalibration.getPower_UVW() < 0) {
                    mViewModel.getPower().setValue((byte) ((beanOfAutoCalibration.getPower_UVW() & 0xFFFF)/1000));
                }else {
                    mViewModel.getPower().setValue((byte) (beanOfAutoCalibration.getPower_UVW()/1000));
                }
                mViewModel.getFreq().setValue((byte) (beanOfAutoCalibration.getFreq()+1));
                mViewModel.getVBusValue().setValue(beanOfAutoCalibration.getVbus_Value()/100F);
                if ((beanOfAutoCalibration.getHandle_ID() == (byte) 0x021)) mViewModel.getHandleType().setValue("1");
                    else mViewModel.getHandleType().setValue("0");
                mViewModel.saveVBusToDataBase();
            }else if (beanOfAutoCalibration.getCmd_type() == 2) {
                mViewModel.getAutoState().setValue("开始自动校准");
            }
        }
    }
}
